package guestbook;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.QueryResultList;
import com.google.appengine.api.datastore.ReadPolicy;

@SuppressWarnings("serial")
public class ListDBEntries extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws ServletException, IOException {

    	// Set the read policy with eventual consistency.
    	ReadPolicy policy = new ReadPolicy(ReadPolicy.Consistency.EVENTUAL);
    	DatastoreServiceConfig eventuallyConsistentConfig = DatastoreServiceConfig.Builder.withReadPolicy(policy);
    	
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(eventuallyConsistentConfig);

        Query q = new Query("SensorData");
        //Query q = new Query("SensorName");
        //q.addFilter("processed", FilterOperator.NOT_EQUAL, false); //damit nicht immer die gleichen Daten re-organisiert werden
		//q.addSort("processed", Query.SortDirection.DESCENDING);
        q.addSort("date", Query.SortDirection.DESCENDING);
        PreparedQuery pq = datastore.prepare(q);
        int pageSize = 999;

        resp.setContentType("text/html");
        
        PrintWriter o = resp.getWriter();
        o.println("<ul>");

        FetchOptions fetchOptions = FetchOptions.Builder.withLimit(pageSize);
        String startCursor = req.getParameter("cursor");

        // If this servlet is passed a cursor parameter, let's use it
        if (startCursor != null) {
            fetchOptions.startCursor(Cursor.fromWebSafeString(startCursor));
        }

        QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
        for (Entity entity : results) {

        	
            	
        	String sens = "";
        	
			o.print(".");
			try {
				sens = entity.getProperty("Sens").toString();
			} catch(NullPointerException ex) {
		  		sens = "SENSOR0";
		  		Entity markVal;
				try {
					markVal = datastore.get(entity.getKey());
					 //zeiger auf aktuelles objekt
					markVal.setProperty("Sens", sens);
					datastore.put(markVal);	// schreiben
					o.println("SnS! ");
					o.println("<li>"+entity.getProperties()+"</li>");
				} catch (EntityNotFoundException e) {
					e.printStackTrace();
				}
			}
			
			@SuppressWarnings("unused")
			Boolean proc = false;
			 
			try {
				proc = Boolean.parseBoolean(entity.getProperty("processed").toString());
			} catch(NullPointerException ex) {
				proc = true;
			}
			/*
			if (proc != false) {
				try { //setzt den processed Marker
					Entity markVal = datastore.get(entity.getKey()); //zeiger auf aktuelles objekt
					markVal.setProperty("processed", false);
		        	datastore.put(markVal);	// schreiben
		        	o.println(proc +"  ");
				} catch (EntityNotFoundException e) {
					e.printStackTrace();
				}
			} 
			*/
        }
        o.println("</ul>");

        String cursor = results.getCursor().toWebSafeString();
        
        if (! results.isEmpty()) {
       
        o.println("<a href='/ListDBEntries?cursor=" + cursor + "'>Next page</a>");
        o.println("<script type=\"text/javascript\">");
        o.println("<!--");
        o.println("window.location = \""+ "/ListDBEntries?cursor=" + cursor +"\"");
        o.println(" //-->");
        o.println("</script>");
        
        }
        
    }
}
